import sys
import os
import json
import logging
from PyQt6.QtWidgets import (QApplication, QMainWindow, QTabWidget, QWidget, 
                           QVBoxLayout, QHBoxLayout, QPushButton, QTextEdit,
                           QLabel, QLineEdit, QFileDialog, QMessageBox,
                           QSystemTrayIcon, QMenu, QComboBox)
from PyQt6.QtCore import QTimer, QSharedMemory
from PyQt6.QtGui import QIcon, QAction, QShortcut, QKeySequence
from InboxSync import (download_from_webdav, upload_to_webdav, 
                           quick_add_to_webdav, init_webdav_client,
                           reset_sync_record)
from global_hotkeys import register_hotkey, start_checking_hotkeys, clear_hotkeys

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S')

class ShortcutInput(QWidget):
    """自定义快捷键输入组件"""
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 修饰键下拉菜单
        self.modifier_combo = QComboBox()
        self.modifier_combo.addItems(["Alt", "Shift+Alt"])
        layout.addWidget(self.modifier_combo)
        
        # 主键输入框
        self.key_input = QLineEdit()
        self.key_input.setMaxLength(1)  # 限制只能输入一个字符
        self.key_input.setPlaceholderText("输入字母")
        layout.addWidget(self.key_input)
        
        # 设置布局比例
        layout.setStretch(0, 2)
        layout.setStretch(1, 1)
        
    def get_shortcut(self):
        """获取完整的快捷键字符串"""
        modifier = self.modifier_combo.currentText()
        key = self.key_input.text().upper()  # 转换为大写
        if not key:
            return ""
        if modifier == "无":
            return key
        return f"{modifier}+{key}"
        
    def set_shortcut(self, shortcut):
        """设置快捷键"""
        if not shortcut:
            self.modifier_combo.setCurrentText("无")
            self.key_input.clear()
            return
            
        parts = shortcut.split("+")
        if len(parts) == 1:
            self.modifier_combo.setCurrentText("无")
            self.key_input.setText(parts[0].upper())
        else:
            modifier = "+".join(parts[:-1])
            key = parts[-1]
            self.modifier_combo.setCurrentText(modifier)
            self.key_input.setText(key.upper())

class InboxSyncGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("InboxSync")
        self.setMinimumSize(400, 300)
        
        # 初始化配置
        if getattr(sys, 'frozen', False):
            # 如果程序被冻结（打包成可执行文件），使用 sys.executable 的目录
            self.conf_dir = os.path.dirname(sys.executable)
        else:
            # 否则使用源码目录
            self.conf_dir = os.path.dirname(os.path.realpath(__file__))
        self.conf_file = "inboxConf.json"
        self.conf = self.load_config()
        
        # 初始化WebDAV客户端
        self.webdav_client = None
        self.init_webdav_client()
        
        # 操作状态标志
        self.is_operating = False
        
        # 创建主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        # 创建主布局
        layout = QVBoxLayout(main_widget)
        
        # 创建选项卡
        tabs = QTabWidget()
        layout.addWidget(tabs)
        
        # 添加同步选项卡
        sync_tab = self.create_sync_tab()
        tabs.addTab(sync_tab, "同步")
        
        # 添加配置选项卡
        config_tab = self.create_config_tab()
        tabs.addTab(config_tab, "配置")
        
        # 添加帮助选项卡
        help_tab = self.create_help_tab()
        tabs.addTab(help_tab, "帮助")
        
        # 创建系统托盘
        self.create_tray_icon()
        
        # 设置快捷键
        self.hotkey_ids = []  # 用于存储注册的快捷键ID
        self.setup_shortcuts()

        # 发送快捷键
        send_shortcut = QShortcut(QKeySequence("Ctrl+S"), self)
        send_shortcut.activated.connect(self.quick_add_note)

    def create_tray_icon(self):
        """创建系统托盘图标"""
        self.tray_icon = QSystemTrayIcon(self)
        # 设置图标
        if getattr(sys, 'frozen', False):
            # 如果程序被冻结（打包成可执行文件），使用 sys._MEIPASS 获取资源路径
            icon_path = os.path.join(sys._MEIPASS, "inbox.png")
        else:
            # 否则使用源码目录
            icon_path = os.path.join(self.conf_dir, "inbox.png")
        
        if os.path.exists(icon_path):
            self.tray_icon.setIcon(QIcon(icon_path))
        
        # 创建托盘菜单
        tray_menu = QMenu()
        
        # 添加菜单项
        show_shortcut = self.conf["settings"].get("show_shortcut", "")
        show_action = QAction(f"主窗口 ({show_shortcut})", self)
        show_action.triggered.connect(self.show)
        tray_menu.addAction(show_action)
        
        # 下载笔记
        download_shortcut = self.conf["settings"].get("download_shortcut", "")
        download_action = QAction(f"下载 ({download_shortcut})", self)
        download_action.triggered.connect(self.download_notes)
        tray_menu.addAction(download_action)
        
        # 上传笔记
        upload_shortcut = self.conf["settings"].get("upload_shortcut", "")
        upload_action = QAction(f"上传 ({upload_shortcut})", self)
        upload_action.triggered.connect(self.upload_notes)
        tray_menu.addAction(upload_action)
        
        tray_menu.addSeparator()
        
        quit_action = QAction("退出", self)
        quit_action.triggered.connect(self.quit_application)
        tray_menu.addAction(quit_action)
        
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()
        
        # 托盘图标双击显示主窗口
        self.tray_icon.activated.connect(self.tray_icon_activated)
        
    def tray_icon_activated(self, reason):
        """处理托盘图标的激活事件"""
        if reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            self.showNormal()
            
        
    def quit_application(self):
        """退出应用程序"""
        clear_hotkeys()
        self.hotkey_ids.clear()

        self.tray_icon.hide()
        QApplication.quit()
        
    def setup_shortcuts(self):
        clear_hotkeys()
        self.hotkey_ids.clear()

        # 定义空的释放回调函数
        def empty_release_callback():
            pass

        # 注册下载快捷键
        download_shortcut = self.conf["settings"].get("download_shortcut", "")
        if download_shortcut:
            hotkey_id = register_hotkey(download_shortcut, self.download_notes, empty_release_callback)
            self.hotkey_ids.append(hotkey_id)

        # 注册上传快捷键
        upload_shortcut = self.conf["settings"].get("upload_shortcut", "")
        if upload_shortcut:
            hotkey_id = register_hotkey(upload_shortcut, self.upload_notes, empty_release_callback)
            self.hotkey_ids.append(hotkey_id)

        # 注册显示主窗口快捷键
        show_shortcut = self.conf["settings"].get("show_shortcut", "")
        if show_shortcut:
            hotkey_id = register_hotkey(show_shortcut, self.show_normal_async, empty_release_callback)
            self.hotkey_ids.append(hotkey_id)

        # 最后启动全局快捷键监听
        start_checking_hotkeys()

    def show_normal_async(self):
        """异步显示主窗口"""
        QTimer.singleShot(0, self.showNormal)

    def load_config(self):
        """加载配置文件"""
        conf_path = os.path.join(self.conf_dir, self.conf_file)
        try:
            with open(conf_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            # 如果配置文件不存在，创建默认配置
            default_conf = {
                "settings": {
                    "webdav_server": "https://dav.jianguoyun.com/dav",
                    "remote_path": "inBox/inBoxData.json",
                    "user_name": "",
                    "password": "",
                    "local_dir": "",
                    "skip_tags": "",
                    "download_shortcut": "Alt+D",
                    "upload_shortcut": "Alt+U",
                    "show_shortcut": "Alt+W"
                }
            }
            with open(conf_path, 'w', encoding='utf-8') as f:
                json.dump(default_conf, f, indent=4, ensure_ascii=False)
            return default_conf
            
    def save_config(self):
        """保存配置文件"""
        conf_path = os.path.join(self.conf_dir, self.conf_file)
        with open(conf_path, 'w', encoding='utf-8') as f:
            json.dump(self.conf, f, indent=4, ensure_ascii=False)
            
    def create_sync_tab(self):
        """创建同步选项卡"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        
        # 下载按钮
        self.download_btn = QPushButton(f"下载 ({self.conf['settings'].get('download_shortcut', '')})")
        self.download_btn.clicked.connect(self.download_notes)
        button_layout.addWidget(self.download_btn)
        
        # 上传按钮
        self.upload_btn = QPushButton(f"上传 ({self.conf['settings'].get('upload_shortcut', '')})")
        self.upload_btn.clicked.connect(self.upload_notes)
        button_layout.addWidget(self.upload_btn)
        
        layout.addLayout(button_layout)
        
        # 快速添加区域
        quick_add_label = QLabel("快速添加笔记：")
        layout.addWidget(quick_add_label)
        
        self.quick_add_text = QTextEdit()
        layout.addWidget(self.quick_add_text)
        
        self.send_btn = QPushButton("发送 (Ctrl+S)")
        self.send_btn.clicked.connect(self.quick_add_note)
        layout.addWidget(self.send_btn)
        
        return tab
        
    def create_config_tab(self):
        """创建配置选项卡"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        # 创建一个固定宽度的容器来对齐所有标签
        container = QWidget()
        container_layout = QVBoxLayout(container)
  
        # WebDAV服务器配置
        common_group = QWidget()
        common_layout = QVBoxLayout(common_group)
        common_layout.setSpacing(15)
  
        # WebDAV服务器地址
        server_layout = QHBoxLayout()
        server_label = QLabel("WebDAV服务器：")
        server_label.setFixedWidth(100)  # 固定标签宽度
        self.server_input = QLineEdit(self.conf["settings"].get("webdav_server", ""))
        self.server_input.setFixedWidth(250)  # 固定输入框宽度
        server_layout.addWidget(server_label)
        server_layout.addWidget(self.server_input)
        server_layout.addStretch()  # 添加弹性空间
        common_layout.addLayout(server_layout)
        
        # 远程路径
        remote_layout = QHBoxLayout()
        remote_label = QLabel("远程路径：")
        remote_label.setFixedWidth(100)
        self.remote_input = QLineEdit(self.conf["settings"].get("remote_path", ""))
        self.remote_input.setFixedWidth(250)
        remote_layout.addWidget(remote_label)
        remote_layout.addWidget(self.remote_input)
        remote_layout.addStretch()
        common_layout.addLayout(remote_layout)
        
        # 用户名
        user_layout = QHBoxLayout()
        user_label = QLabel("用户名：")
        user_label.setFixedWidth(100)
        self.user_input = QLineEdit(self.conf["settings"].get("user_name", ""))
        self.user_input.setFixedWidth(250)
        user_layout.addWidget(user_label)
        user_layout.addWidget(self.user_input)
        user_layout.addStretch()
        common_layout.addLayout(user_layout)
        
        # 密码
        password_layout = QHBoxLayout()
        password_label = QLabel("密码：")
        password_label.setFixedWidth(100)
        self.password_input = QLineEdit(self.conf["settings"].get("password", ""))
        self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
        self.password_input.setFixedWidth(250)
        password_layout.addWidget(password_label)
        password_layout.addWidget(self.password_input)
        password_layout.addStretch()
        common_layout.addLayout(password_layout)
        
        # 本地目录配置
        local_dir_layout = QHBoxLayout()
        local_dir_label = QLabel("本地目录：")
        local_dir_label.setFixedWidth(100)
        self.local_dir_input = QLineEdit(self.conf["settings"].get("local_dir", ""))
        self.local_dir_input.setFixedWidth(250)
        browse_btn = QPushButton("浏览")
        browse_btn.setFixedWidth(60)
        browse_btn.clicked.connect(self.browse_local_dir)
        local_dir_layout.addWidget(local_dir_label)
        local_dir_layout.addWidget(self.local_dir_input)
        local_dir_layout.addWidget(browse_btn)
        local_dir_layout.addStretch()
        common_layout.addLayout(local_dir_layout)

        # 跳过标签配置
        skip_tags_layout = QHBoxLayout()
        skip_tags_label = QLabel("跳过标签：")
        skip_tags_label.setFixedWidth(100)
        self.skip_tags_input = QLineEdit(self.conf["settings"].get("skip_tags", ""))
        self.skip_tags_input.setFixedWidth(250)
        skip_tags_layout.addWidget(skip_tags_label)
        skip_tags_layout.addWidget(self.skip_tags_input)
        skip_tags_layout.addStretch()
        common_layout.addLayout(skip_tags_layout)

        # 快捷键配置
        
        # 下载快捷键
        download_shortcut_layout = QHBoxLayout()
        download_shortcut_label = QLabel("下载快捷键：")
        download_shortcut_label.setFixedWidth(100)
        self.download_shortcut_input = ShortcutInput()
        self.download_shortcut_input.setFixedWidth(250)
        self.download_shortcut_input.set_shortcut(self.conf["settings"].get("download_shortcut", ""))
        download_shortcut_layout.addWidget(download_shortcut_label)
        download_shortcut_layout.addWidget(self.download_shortcut_input)
        download_shortcut_layout.addStretch()
        common_layout.addLayout(download_shortcut_layout)
        
        # 上传快捷键
        upload_shortcut_layout = QHBoxLayout()
        upload_shortcut_label = QLabel("上传快捷键：")
        upload_shortcut_label.setFixedWidth(100)
        self.upload_shortcut_input = ShortcutInput()
        self.upload_shortcut_input.setFixedWidth(250)
        self.upload_shortcut_input.set_shortcut(self.conf["settings"].get("upload_shortcut", ""))
        upload_shortcut_layout.addWidget(upload_shortcut_label)
        upload_shortcut_layout.addWidget(self.upload_shortcut_input)
        upload_shortcut_layout.addStretch()
        common_layout.addLayout(upload_shortcut_layout)
        
        # 显示主窗口快捷键
        show_shortcut_layout = QHBoxLayout()
        show_shortcut_label = QLabel("显示主窗口快捷键：")
        show_shortcut_label.setFixedWidth(100)
        self.show_shortcut_input = ShortcutInput()
        self.show_shortcut_input.setFixedWidth(250)
        self.show_shortcut_input.set_shortcut(self.conf["settings"].get("show_shortcut", ""))
        show_shortcut_layout.addWidget(show_shortcut_label)
        show_shortcut_layout.addWidget(self.show_shortcut_input)
        show_shortcut_layout.addStretch()
        common_layout.addLayout(show_shortcut_layout)
        
        container_layout.addWidget(common_group)

        end_group = QWidget()
        end_layout = QVBoxLayout(end_group)
        end_layout.setSpacing(0)
        container_layout.addWidget(end_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
    
        # 保存按钮
        save_btn = QPushButton("保存配置")
        save_btn.setFixedWidth(100)
        save_btn.clicked.connect(self.save_settings)
        button_layout.addWidget(save_btn)
        
        # 重置同步记录按钮
        reset_btn = QPushButton("重置同步记录")
        reset_btn.setFixedWidth(100)
        reset_btn.clicked.connect(self.reset_sync_record)
        button_layout.addWidget(reset_btn)
        
        button_layout.addStretch()
        container_layout.addLayout(button_layout)
        
        # 将容器添加到主布局
        layout.addWidget(container)
        
        return tab
        
    def create_help_tab(self):
        """创建帮助选项卡"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        help_text = """

        <p>InboxSync是一个用于同步Inbox笔记的桌面应用程序，支持将WebDAV中的Inbox笔记内容与电脑端文件夹中的Markdown笔记进行双向同步。</p>

        <p>项目主页：<a href="https://gitee.com/jjtenger/inbox-pc-sync">GitHub</a></p>

        <p>作者：jjtenger</p>

        """
        
        help_label = QLabel(help_text)
        help_label.setOpenExternalLinks(True)
        help_label.setWordWrap(True)
        layout.addWidget(help_label)
        # 添加一个可伸缩的空间，使内容居上对齐
        layout.addStretch(1)
        return tab
        
    def browse_local_dir(self):
        """浏览本地目录"""
        dir_path = QFileDialog.getExistingDirectory(
            self,
            "选择本地目录",
            self.local_dir_input.text()
        )
        if dir_path:
            # 标准化路径
            normalized_path = os.path.normpath(dir_path)
            self.local_dir_input.setText(normalized_path)
            
    def init_webdav_client(self):
        """初始化WebDAV客户端"""
        try:
            self.webdav_client = init_webdav_client(self.conf)
        except Exception as e:
            logging.error(f"初始化WebDAV客户端失败：{str(e)}")
            self.webdav_client = None
            
    def check_config(self):
        """检查配置是否完整"""
        settings = self.conf.get("settings", {})
        required_fields = {
            "webdav_server": "WebDAV服务器地址",
            "user_name": "用户名",
            "password": "密码",
            "remote_path": "远程路径",
            "local_dir": "本地目录"
        }
        
        # 检查必填字段
        missing_fields = []
        for field, name in required_fields.items():
            if not settings.get(field, "").strip():
                missing_fields.append(name)
                
        if missing_fields:
            self.tray_icon.showMessage("警告", f"以下配置项未设置：\n{', '.join(missing_fields)}\n请先在配置选项卡中设置这些选项。", QSystemTrayIcon.MessageIcon.Warning, 5000)
            return False
            
        # 检查本地目录是否存在
        local_dir = settings.get("local_dir", "").strip()
        if not os.path.exists(local_dir):
            try:
                os.makedirs(local_dir)
            except Exception as e:
                self.tray_icon.showMessage(
                    "错误",
                    f"无法创建本地目录：{local_dir}\n错误信息：{str(e)}",
                    QSystemTrayIcon.MessageIcon.Critical,
                    5000
                )
                return False
                
        # 重新初始化WebDAV客户端
        self.init_webdav_client()
        if not self.webdav_client:
            self.tray_icon.showMessage("错误", "无法连接到WebDAV服务器，请检查服务器配置是否正确。", QSystemTrayIcon.MessageIcon.Critical, 5000)
            return False
                
        return True
        
    def save_settings(self):
        """保存设置"""
        try:
            self.conf["settings"]["webdav_server"] = self.server_input.text()
            self.conf["settings"]["remote_path"] = self.remote_input.text()
            self.conf["settings"]["user_name"] = self.user_input.text()
            self.conf["settings"]["password"] = self.password_input.text()
            self.conf["settings"]["local_dir"] = self.local_dir_input.text()
            self.conf["settings"]["skip_tags"] = self.skip_tags_input.text()
            self.conf["settings"]["download_shortcut"] = self.download_shortcut_input.get_shortcut()
            self.conf["settings"]["upload_shortcut"] = self.upload_shortcut_input.get_shortcut()
            self.conf["settings"]["show_shortcut"] = self.show_shortcut_input.get_shortcut()
            
            self.save_config()
            self.setup_shortcuts()  # 重新设置快捷键
            
            # 更新按钮的快捷键文本描述
            self.download_btn.setText(f"下载 ({self.conf['settings'].get('download_shortcut', '')})")
            self.upload_btn.setText(f"上传 ({self.conf['settings'].get('upload_shortcut', '')})")
            
            # 更新托盘菜单的快捷键文本描述
            tray_menu = self.tray_icon.contextMenu()
            for action in tray_menu.actions():
                if action.text().startswith("主窗口"):
                    action.setText(f"主窗口 ({self.conf['settings'].get('show_shortcut', '')})")
                elif action.text().startswith("下载"):
                    action.setText(f"下载 ({self.conf['settings'].get('download_shortcut', '')})")
                elif action.text().startswith("上传"):
                    action.setText(f"上传 ({self.conf['settings'].get('upload_shortcut', '')})")
            
            # 重新初始化WebDAV客户端
            self.init_webdav_client()
            if not self.webdav_client:
                self.tray_icon.showMessage(
                    "警告",
                    "保存配置成功，但无法连接到WebDAV服务器，请检查服务器配置。",
                    QSystemTrayIcon.MessageIcon.Warning,
                    5000
                )
            else:
                self.tray_icon.showMessage("成功", "配置已保存", QSystemTrayIcon.MessageIcon.Information, 2000)
        except Exception as e:
            self.tray_icon.showMessage("错误", f"保存配置失败：{str(e)}", QSystemTrayIcon.MessageIcon.Critical, 5000)
            
    def set_operating_state(self, is_operating):
        """设置操作状态"""
        self.is_operating = is_operating
        # 更新按钮状态
        self.download_btn.setEnabled(not is_operating)
        self.upload_btn.setEnabled(not is_operating)
        self.send_btn.setEnabled(not is_operating)
        self.quick_add_text.setEnabled(not is_operating)
        
    def download_notes(self):
        """下载笔记"""
        if self.is_operating:
            self.tray_icon.showMessage(
                    "警告",
                    "当前有操作正在执行，请等待完成",
                    QSystemTrayIcon.MessageIcon.Warning,
                    2000
                )
            return
            
        if not self.check_config():
            return

        # 使用 QTimer.singleShot 异步执行下载逻辑
        QTimer.singleShot(0, self._async_download_notes)

    def _async_download_notes(self):
        """异步执行下载笔记逻辑"""
        try:
            self.set_operating_state(True)
            local_dir = self.conf["settings"].get("local_dir", self.conf_dir)
            download_from_webdav(self.conf, self.conf_dir, local_dir, self.webdav_client)
            self.tray_icon.showMessage("成功", "下载成功！", QSystemTrayIcon.MessageIcon.Information, 2000)
        except Exception as e:
            self.tray_icon.showMessage("错误", f"下载失败：{str(e)}", QSystemTrayIcon.MessageIcon.Critical, 5000)
        finally:
            self.set_operating_state(False)

    def upload_notes(self):
        """上传笔记"""
        if self.is_operating:
            self.tray_icon.showMessage(
                    "警告",
                    "当前有操作正在执行，请等待完成",
                    QSystemTrayIcon.MessageIcon.Warning,
                    2000
                )
            return
            
        if not self.check_config():
            return

        # 使用 QTimer.singleShot 异步执行上传逻辑
        QTimer.singleShot(0, self._async_upload_notes)

    def _async_upload_notes(self):
        """异步执行上传笔记逻辑"""
        try:
            self.set_operating_state(True)
            local_dir = self.conf["settings"].get("local_dir", self.conf_dir)
            upload_to_webdav(self.conf, self.conf_dir, local_dir, self.webdav_client)
            self.tray_icon.showMessage("成功", "上传成功！", QSystemTrayIcon.MessageIcon.Information, 2000)
        except Exception as e:
            self.tray_icon.showMessage("错误", f"上传失败：{str(e)}", QSystemTrayIcon.MessageIcon.Critical, 5000)
        finally:
            self.set_operating_state(False)
            
    def quick_add_note(self):
        """快速添加笔记"""
        if self.is_operating:
            self.tray_icon.showMessage(
                    "警告",
                    "当前有操作正在执行，请等待完成",
                    QSystemTrayIcon.MessageIcon.Warning,
                    2000
                )
            return
            
        if not self.check_config():
            return
            
        try:
            content = self.quick_add_text.toPlainText().strip()
            if not content:
                self.tray_icon.showMessage(
                    "警告",
                    "请输入笔记内容",
                    QSystemTrayIcon.MessageIcon.Warning,
                    2000
                )
                return
                
            self.set_operating_state(True)
            local_dir = self.conf["settings"].get("local_dir", self.conf_dir)
            quick_add_to_webdav(self.conf, self.conf_dir, local_dir, content, self.webdav_client)
            self.quick_add_text.clear()
            self.tray_icon.showMessage("成功", "发送成功！", QSystemTrayIcon.MessageIcon.Information, 2000)
        except Exception as e:
            self.tray_icon.showMessage("错误", f"发送失败：{str(e)}", QSystemTrayIcon.MessageIcon.Critical, 5000)
        finally:
            self.set_operating_state(False)

    def reset_sync_record(self):
        """重置同步记录"""
        try:
            reply = QMessageBox.question(
                self,
                "确认重置",
                "确定要重置同步记录吗？这将清除所有同步状态，下次同步时会重新检查所有文件。",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                reset_sync_record(self.conf, self.conf_dir)
                self.tray_icon.showMessage("成功", "同步记录已重置", QSystemTrayIcon.MessageIcon.Information, 2000)
        except Exception as e:
            self.tray_icon.showMessage("错误", f"重置同步记录失败：{str(e)}", QSystemTrayIcon.MessageIcon.Critical, 5000)

    def closeEvent(self, event):
        """重写关闭事件"""
        event.ignore()
        self.hide()
        self.tray_icon.showMessage(
            "InboxSync",
            "应用程序已最小化到系统托盘",
            QSystemTrayIcon.MessageIcon.Information,
            2000
        )

# 打包命令
# pyinstaller --name=InboxSync --onefile --windowed --icon=inbox.ico --add-data "inbox.png;." InboxSync_gui.py
# pyinstaller InboxSync.spec

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 使用QSharedMemory来确保只有一个实例运行
    shared_memory = QSharedMemory("InboxSyncApp")
    if not shared_memory.create(1):
        QMessageBox.warning(None, "警告", "应用程序已经在运行中。")
        sys.exit(1)
    
    window = InboxSyncGUI()
    window.show()
    sys.exit(app.exec())